﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Linq.Expressions;
using QLHD.Models;
using QLHD.WS;
using QLHD.Utilities;
using System.Globalization;

namespace QLHD
{
    public partial class Khoanchiphi : System.Web.UI.Page
    {
        int pagesize = 9999;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack)
                return;

            Session["viewonly"] = false;
            List<PhongBan> viewphongbanids = new AuthenticationHelper().GetListPhongban();
            //List<PhongBan> viewphongbanids = new QLHD2013Entities().PhongBans.Where(q => q.TrangThai == true).ToList();
            var pbs = ((from item in viewphongbanids
                        select new
                        {
                            ID = item.ID,
                            Ten = item.Ten
                        })).ToList();

            chklphongban.DataSource = pbs;
            chklphongban.DataBind();

            foreach (ListItem item in chklphongban.Items)
            {
                item.Selected = true;
            }

            btnExpExcel.Enabled = false;

            if (Session["fromdate"] != null)
            {
                DateTime fromdate = (DateTime)Session["fromdate"];
            }

            if (Session["todate"] != null)
            {
                DateTime fromdate = (DateTime)Session["todate"];

            }

            if (Session["slroomid"] != null)
            {
                List<int> slroomid = (List<int>)Session["slroomid"];
                foreach (ListItem item in chklphongban.Items)
                {
                    if (slroomid.Contains(int.Parse(item.Value)))
                    {
                        item.Selected = true;
                    }
                }
            }

            if (Session["trangthai"] != null)
            {
                chktrangthai.SelectedValue = Session["trangthai"].ToString();
            }

            rptKcp.DataSource = ListKCP();
            rptKcp.DataBind();
            QLHD2013Entities db = new QLHD2013Entities();
            var notifycount = db.HopDongs.Where(q => q.KhoanChiPhis.Where(q1 => q1.KhoanChiPhi2 == null && (q1.CPGK_Total != null || q1.CPTH_Total != null) && q1.CPGK_Total != q1.CPTH_Total).Count() > 0).Count();

            if (notifycount > 0)
            {
                divNotify.InnerText = string.Format(divNotify.InnerText, notifycount);
            }
            else
            {
                divNotify.Visible = false;
            }
        }

        public int GetColspan(string group)
        {
            int colspan = 0;
            switch (group.ToLower())
            {
                case "hopdong":
                    colspan += chksohd.Checked ? 1 : 0;
                    colspan += chkngayhd.Checked ? 1 : 0;
                    colspan += chkgiatrihd.Checked ? 1 : 0;
                    break;
                case "kcp":
                    colspan += chksokcp.Checked ? 1 : 0;
                    colspan += chkngaykcp.Checked ? 1 : 0;
                    colspan += chkgiatrikcp.Checked ? 1 : 0;
                    break;
                case "ctcpgk":
                    colspan += chkctgktttc.Checked ? 1 : 0;
                    colspan += chkctgkquacty.Checked ? 1 : 0;
                    colspan += chkctgktkcm.Checked ? 1 : 0;
                    colspan += chkctgkthuechuyengia.Checked ? 1 : 0;
                    colspan += chkctgkptmtn.Checked ? 1 : 0;
                    colspan += chkctgkptmmt.Checked ? 1 : 0;
                    colspan += chkctgkhoachat.Checked ? 1 : 0;
                    colspan += chkctgkthuemuangoai.Checked ? 1 : 0;
                    colspan += chkctgkluong.Checked ? 1 : 0;

                    colspan += chkctgknvl.Checked ? 1 : 0;
                    colspan += chkctgkcpk.Checked ? 1 : 0;
                    break;
                case "ctcpth":
                    colspan += chkctthtttc.Checked ? 1 : 0;
                    colspan += chkctthchiquacty.Checked ? 1 : 0;
                    colspan += chkctthtkcm.Checked ? 1 : 0;
                    colspan += chkctththuechuyengia.Checked ? 1 : 0;
                    colspan += chkctthptmtn.Checked ? 1 : 0;
                    colspan += chkctthptmmt.Checked ? 1 : 0;
                    colspan += chkctthhoachat.Checked ? 1 : 0;
                    colspan += chkctththuemuangoai.Checked ? 1 : 0;
                    colspan += chkctthluong.Checked ? 1 : 0;

                    colspan += chkctthnvl.Checked ? 1 : 0;
                    colspan += chkctthcpk.Checked ? 1 : 0;

                    break;
                case "gkthuemuangoai":
                    colspan += chkctgktkcm.Checked ? 1 : 0;
                    colspan += chkctgkthuechuyengia.Checked ? 1 : 0;
                    colspan += chkctgkptmtn.Checked ? 1 : 0;
                    colspan += chkctgkptmmt.Checked ? 1 : 0;
                    colspan += chkctgkhoachat.Checked ? 1 : 0;
                    colspan += chkctgkthuemuangoai.Checked ? 1 : 0;
                    break;
                case "ththuemuangoai":
                    colspan += chkctthtkcm.Checked ? 1 : 0;
                    colspan += chkctththuechuyengia.Checked ? 1 : 0;
                    colspan += chkctthptmtn.Checked ? 1 : 0;
                    colspan += chkctthptmmt.Checked ? 1 : 0;
                    colspan += chkctthhoachat.Checked ? 1 : 0;
                    colspan += chkctththuemuangoai.Checked ? 1 : 0;
                    break;
                case "quyettoan":
                    colspan += chksoquyettoan.Checked ? 1 : 0;
                    colspan += chkngayquyettoan.Checked ? 1 : 0;
                    colspan += chkgiatriquyettoan.Checked ? 1 : 0;
                    break;
            }
            return colspan;
        }

        protected void btnShow_Click(object sender, EventArgs e)
        {
            rptKcp.DataSource = ListKCP();
            rptKcp.DataBind();
        }

        public object ListKCP()
        {
            int page = 1;
            if (Request.Params["page"] != null)
            {
                page = int.Parse(Request.Params["page"]);
            }

            List<int> viewphongbanids = new hdservice().GetViewDepartmentIDs();

            QLHD2013Entities db = new QLHD2013Entities();

            List<HopDong> lsthopdong = new List<HopDong>();

            int mahopdong = 0;
            //if (!string.IsNullOrEmpty(keyword))
            //    mahopdong = int.Parse(keyword);

            List<KhoanChiPhi> lstxnkl = null;
            int total = 0;



            if (mahopdong > 0)
            {
                lsthopdong = db.HopDongs.Where(IsContain(viewphongbanids).Compile())
               .Where(q =>
                   q.TrangThaiHD == 1
                   && q.MaHD == mahopdong
                   && (q.ParentID == null || q.ParentID == 0)).ToList();
                total = lsthopdong.Count();
            }
            else
            {
                List<hd> lst = new List<hd>();
                string fromd = txtfromdate.Text;
                string tod = txttodate.Text;
                //int departmentid = int.Parse(drphongban.SelectedValue);
                string trangthai = chktrangthai.SelectedValue;

                List<int> slroomid = new List<int>();

                foreach (ListItem item1 in chklphongban.Items)
                {
                    if (item1.Selected == true)
                    {
                        slroomid.Add(int.Parse(item1.Value));
                    }
                }

                hdservice ut = new hdservice();

                DateTime fromdate = DateTime.Parse("01/01/1901 00:00:00");
                DateTime todate = DateTime.Parse("09/09/2099 23:59:59");

                Session["fromdate"] = fromdate;
                Session["todate"] = todate;
                Session["slroomid"] = slroomid;
                Session["trangthai"] = trangthai;
                var provider = new CultureInfo("vi-VN");
                if (!string.IsNullOrEmpty(fromd))
                    fromdate = Convert.ToDateTime(fromd + " 00:00:00", provider);

                if (!string.IsNullOrEmpty(tod))
                    todate = Convert.ToDateTime(tod + " 23:59:59", provider);

                if (!string.IsNullOrEmpty(Request.Params["notify"]))
                {
                    lsthopdong = db.HopDongs.Where(q =>
                        q.TrangThaiHD == 1
                        && q.KhoanChiPhis.Where(q1 => (q1.CPGK_Total > 0 || q1.CPTH_Total > 0) && q1.CPTH_Total != q1.CPGK_Total).Count() > 0
                        && (q.ParentID == null || q.ParentID == 0)
                        && q.NgayTaoHD >= fromdate && q.NgayTaoHD <= todate
                        && q.DepartmentID != null
                        ).ToList();



                    //lsthopdong = db.HopDongs.Where(q =>
                    //    q.TrangThaiHD == 1
                    //    && (
                    //      q.KhoanChiPhis.Sum(k=>
                    //        k.CPGK_CPK+k.CPGK_HoaChat+k.CPGK_Luong+k.CPGK_NVL+k.CPGK_PTMauMT+k.CPGK_PTMauTN+k.CPGK_QuaCTy+k.CPGK_ThueChuyenGia+k.CPGK_Thuemuangoai+k.CPGK_TKCM+k.CPGK_TTTC)
                    //      !=
                    //      q.KhoanChiPhis.Sum(k=>
                    //        k.CPTH_CPK+k.CPTH_HoaChat+k.CPTH_Luong+k.CPTH_NVL+k.CPTH_PTMauMT+k.CPTH_PTMauTN+k.CPTH_QuaCty+k.CPTH_ThueChuyenGia+k.CPTH_Thuemuangoai+k.CPTH_TKCM+k.CPTH_TTTC)
                    //        )
                    //    && (q.ParentID == null || q.ParentID == 0)
                    //        //&& q.DepartmentID == departmentid
                    //    && q.NgayTaoHD >= fromdate && q.NgayTaoHD <= todate
                    //    && q.DepartmentID != null
                    //    ).ToList();
                }
                else
                {

                    lsthopdong = db.HopDongs.Where(q =>
                        q.TrangThaiHD == 1
                        && (q.ParentID == null || q.ParentID == 0)
                            //&& q.DepartmentID == departmentid
                        && q.NgayTaoHD >= fromdate && q.NgayTaoHD <= todate
                        && q.DepartmentID != null
                        ).ToList();
                }

                DateTime today = DateTime.Today;
                today = new DateTime(today.Year, today.Month, today.Day, 0, 0, 0);

                lsthopdong.RemoveAll(q => q.DepartmentID != null && (!viewphongbanids.Contains((int)q.DepartmentID)));
                lsthopdong.RemoveAll(q => q.DepartmentID != null && (!slroomid.Contains((int)q.DepartmentID)));
                //trang thai
                if (trangthai == "done")
                {
                    lsthopdong.RemoveAll(q => q.NgayThanhLyHD == null || q.GiaTriThanhLyHD == null || q.GiaTriThanhLyHD <= 0);
                }
                else if (trangthai == "doing")
                {
                    lsthopdong.RemoveAll(q => q.NgayThanhLyHD != null || q.GiaTriThanhLyHD > 0);
                }

                total = lsthopdong.Count();

                lsthopdong = lsthopdong.OrderByDescending(q => q.MaHD).Skip((page - 1) * pagesize).Take(pagesize).ToList();

                //total = db.HopDongs.Where(IsContain(viewphongbanids).Compile())
                //.Where(q =>
                //    q.TrangThaiHD == 1
                //    && (q.ParentID == null || q.ParentID == 0)
                //    //&& (q.SearchContent.Contents.Contains(keyword))
                //    ).Count();

                if (lsthopdong.Count() > 0)
                    btnExpExcel.Enabled = true;
            }

            GenaratePager(page, pagesize, total);

            List<dynamic> source = new List<dynamic>();
            int num = 1;
            int i = 1;
            foreach (HopDong hd in lsthopdong)
            {
                source.Add(GetKCPModel(hd, ((page - 1) * pagesize + i).ToString()));

                var kcps = hd.KhoanChiPhis.Where(q => q.ParentID == null && q.TrangThai == true).ToList();
                int j = 1;
                foreach (KhoanChiPhi kcp in kcps)
                {
                    num = 1;
                    var children = GetKCPChildren(kcp, ((page - 1) * pagesize + i).ToString() + "." + j.ToString(), out num);
                    //var totalcpgk = children.Sum(q => (decimal)q.Total_CPGK);
                    //var totalcpth = children.Sum(q => (decimal)q.Total_CPTH);

                    var _kcp = GetKCPModel(kcp, ((page - 1) * pagesize + i).ToString() + "." + j.ToString(), -1, -1);
                    source.Add(_kcp);
                    source.AddRange(children);

                    j++;
                }

                i++;
            }
            return source;
        }

        private static List<dynamic> GetKCPChildren(KhoanChiPhi root, string firstnumber, out int num, int startnum = 1)
        {
            List<dynamic> child = new List<dynamic>();
            num = 0;
            if (root.KhoanChiPhi1 == null && root.KhoanChiPhi1.Where(q => q.TrangThai == true).Count() == 0)
                return child;
            int i = 0;
            int j = 0;
            foreach (KhoanChiPhi item in root.KhoanChiPhi1.Where(q => q.TrangThai == true))
            {
                string fn = string.IsNullOrEmpty(firstnumber) ? "" : firstnumber + "." + (i + startnum);
                string fn1 = string.IsNullOrEmpty(firstnumber) ? "" : firstnumber + "." + (i + 1);
                child.Add(GetKCPModel(item, fn));
                child.AddRange(GetKCPChildren(item, "", out j));
                i++;
            }
            num = i;
            return child;
        }

        private static dynamic GetKCPModel(KhoanChiPhi item, string firstnumber, decimal totalcpgk = -1, decimal totalcpth = -1)
        {
            return new
            {
                STT = firstnumber,
                Noidung = item.NoiDung,
                SoHD = "",
                NgayTaoHD = "",
                GiaTriHD = "",
                Phong = "",
                Tiendothuchien = "",

                MaKCP = item.MaKCP,
                MaHD = item.MaHD,
                SoKCP = item.SoKCP,
                GiaTri = Utilities.Utilities.GetDecimalValue(item.GiaTri),
                GhiChu = item.GhiChu,

                CPGK_TTTC = Utilities.Utilities.GetDecimalValue(item.CPGK_TTTC, true),
                CPGK_QuaCTy = Utilities.Utilities.GetDecimalValue(item.CPGK_QuaCTy, true),
                CPGK_TKCM = Utilities.Utilities.GetDecimalValue(item.CPGK_TKCM, true),
                CPGK_ThueChuyenGia = Utilities.Utilities.GetDecimalValue(item.CPGK_ThueChuyenGia, true),
                CPGK_PTMauTN = Utilities.Utilities.GetDecimalValue(item.CPGK_PTMauTN, true),
                CPGK_PTMauMT = Utilities.Utilities.GetDecimalValue(item.CPGK_PTMauMT, true),
                CPGK_HoaChat = Utilities.Utilities.GetDecimalValue(item.CPGK_HoaChat, true),
                CPGK_Luong = Utilities.Utilities.GetDecimalValue(item.CPGK_Luong, true),
                CPGK_Thuemuangoai = Utilities.Utilities.GetDecimalValue(item.CPGK_Thuemuangoai, true),
                CPGK_NVL = Utilities.Utilities.GetDecimalValue(item.CPGK_NVL, true),
                CPGK_CPK = Utilities.Utilities.GetDecimalValue(item.CPGK_CPK, true),
                //Total_CPGK = totalcpgk < 0 ? (item.KhoanChiPhi2 != null ? item.CPGK_TTTC + item.CPGK_QuaCTy + item.CPGK_TKCM + item.CPGK_ThueChuyenGia + item.CPGK_PTMauTN + item.CPGK_PTMauMT
                //            + item.CPGK_HoaChat + item.CPGK_Luong + item.CPGK_Thuemuangoai + item.CPGK_NVL + item.CPGK_CPK : 0) : totalcpgk,
                Total_CPGK = Utilities.Utilities.GetDecimalValue(item.CPGK_Total,false),
                CPTH_TTTC = Utilities.Utilities.GetDecimalValue(item.CPTH_TTTC, true),
                CPTH_QuaCty = Utilities.Utilities.GetDecimalValue(item.CPTH_QuaCty, true),
                CPTH_TKCM = Utilities.Utilities.GetDecimalValue(item.CPTH_TKCM, true),
                CPTH_ThueChuyenGia = Utilities.Utilities.GetDecimalValue(item.CPTH_ThueChuyenGia, true),
                CPTH_PTMauTN = Utilities.Utilities.GetDecimalValue(item.CPTH_PTMauTN, true),
                CPTH_PTMauMT = Utilities.Utilities.GetDecimalValue(item.CPTH_PTMauMT, true),
                CPTH_HoaChat = Utilities.Utilities.GetDecimalValue(item.CPTH_HoaChat, true),
                CPTH_Luong = Utilities.Utilities.GetDecimalValue(item.CPTH_Luong, true),
                CPTH_Thuemuangoai = Utilities.Utilities.GetDecimalValue(item.CPTH_Thuemuangoai, true),
                CPTH_NVL = Utilities.Utilities.GetDecimalValue(item.CPTH_NVL, true),
                CPTH_CPK = Utilities.Utilities.GetDecimalValue(item.CPTH_CPK, true),
                //Total_CPTH = totalcpth < 0 ? (item.KhoanChiPhi2 != null ? item.CPTH_TTTC + item.CPTH_QuaCty + item.CPTH_TKCM + item.CPTH_ThueChuyenGia + item.CPTH_PTMauTN + item.CPTH_PTMauMT
                //            + item.CPTH_HoaChat + item.CPTH_Luong + item.CPTH_Thuemuangoai + item.CPTH_NVL + item.CPTH_CPK : 0) : totalcpth,

                Total_CPTH = Utilities.Utilities.GetDecimalValue(item.CPTH_Total, false),
                QuyetToan_So = item.QuyetToan_So,
                QuyetToan_Ngay = item.QuyetToan_Ngay != null ? ((DateTime)item.QuyetToan_Ngay).ToString("dd/MM/yyyy") : "",
                QuyetToan_Giatri = item.QuyetToan_Giatri,

                Ngay = item.Ngay != null ? ((DateTime)item.Ngay).ToString("dd/MM/yyyy") : "",
                ParentID = item.ParentID != null ? item.ParentID.ToString() : "0",
                IsLeaf = item.KhoanChiPhi2 != null ? "1" : "0"
                // && item.KhoanChiPhi2.KhoanChiPhi2 != null
            };
        }

        private static dynamic GetKCPModel(HopDong item, string firstnumber)
        {
            return new
            {
                STT = firstnumber,
                Noidung = item.TenHD,
                SoHD = item.SoHD,
                NgayTaoHD = item.NgayTaoHD != null ? item.NgayTaoHD.ToString("dd/MM/yyyy") : "",
                GiaTriHD = Utilities.Utilities.GetDecimalValue(item.GiaTriHD),
                Phong = item.PhongBan != null ? item.PhongBan.Ten : "",
                Tiendothuchien = item.TienDoThucHien,

                MaKCP = 0,
                MaHD = item.MaHD,
                SoKCP = "",

                GiaTri = "",
                GhiChu = "",

                CPGK_TTTC = "",
                CPGK_QuaCTy = "",
                CPGK_TKCM = "",
                CPGK_ThueChuyenGia = "",
                CPGK_PTMauTN = "",
                CPGK_PTMauMT = "",
                CPGK_HoaChat = "",
                CPGK_Luong = "",
                CPGK_Thuemuangoai = "",
                CPGK_NVL = "",
                CPGK_CPK = "",
                Total_CPGK = 0,

                CPTH_TTTC = "",
                CPTH_QuaCty = "",
                CPTH_TKCM = "",
                CPTH_ThueChuyenGia = "",
                CPTH_PTMauTN = "",
                CPTH_PTMauMT = "",
                CPTH_HoaChat = "",
                CPTH_Luong = "",
                CPTH_Thuemuangoai = "",
                CPTH_NVL = "",
                CPTH_CPK = "",
                Total_CPTH = 0,

                QuyetToan_So = "",
                QuyetToan_Ngay = "",
                QuyetToan_Giatri = "",

                Ngay = "",
                ParentID = "0",
                IsLeaf = "-1"

            };
        }

        private static Expression<Func<HopDong, bool>> IsContain(List<int> lst)
        {
            return p => lst.Where(e => e == p.DepartmentID).Count() > 0;
        }

        private void GenaratePager(int currentpage, int pagesize, int totalrecord)
        {
            int totalpage = totalrecord / pagesize + (totalrecord % pagesize > 0 ? 1 : 0);

            string[] arrp = new string[totalpage];
            rptpage.DataSource = arrp;
            rptpage.DataBind();
        }

        protected void btnExpExcel_Click(object sender, EventArgs e)
        {
            Response.Clear();
            Response.Buffer = true;
            string filename = "Khoan chi phi - " + DateTime.Today.ToString("dd-MM-yyyy") + ".xls";
            Response.AddHeader("content-disposition", "attachment;filename=" + filename);
            Response.Charset = "";
            Response.ContentType = "application/vnd.ms-excel";

            System.IO.StringWriter stringWrite = new System.IO.StringWriter();
            System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
            //     Your Repeater Name Mine is "Rep"
            rptKcp.RenderControl(htmlWrite);
            Response.Write("<table>");
            Response.Write(stringWrite.ToString());
            Response.Write("</table>");
            Response.End();
        }

        protected void rptKcp_ItemCommand(object Sender, RepeaterCommandEventArgs e)
        {
            int makcp = int.Parse(e.CommandArgument.ToString());
            QLHD2013Entities db = new QLHD2013Entities();
            var target = db.KhoanChiPhis.Where(q => q.MaKCP == makcp).FirstOrDefault();
            if (target != null)
            {
                db.DeleteObject(target);
                db.SaveChanges();

                rptKcp.DataSource = ListKCP();
                rptKcp.DataBind();
            }
        }

        protected void rptKcp_ItemDataBound(object Sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                dynamic d = e.Item.DataItem;
                if (d.IsLeaf != "1")
                {
                    Button btndelete = (Button)e.Item.FindControl("btnDelete");
                    if (btndelete != null)
                    {
                        btndelete.CommandArgument = d.MaKCP.ToString();
                    }
                }
            }
        }

        public override void VerifyRenderingInServerForm(Control control)
        {
            /* Confirms that an HtmlForm control is rendered for the specified ASP.NET
               server control at run time. */
        }


    }
}